<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\MoneyBook;
use App\Models\MoneyCategory;
use App\Models\MoneySubCategory;
use App\Models\MoneyBookUser;
use App\Models\AutoMoneyTransaction;

class MoneyCategoryController extends Controller
{
    /**
     * 显示分类管理页面
     */
    public function index($bookId)
    {
        $user = Auth::user();

        // 验证账本权限
        $book = MoneyBook::whereHas('users', function($query) use ($user) {
            $query->where('user_id', $user->id);
        })->findOrFail($bookId);

        return view('user.category-management', compact('book'));
    }

    /**
     * 获取分类列表
     */
    public function getCategories($bookId, $type = null)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            $query = MoneyCategory::where('book_id', $bookId)
                                 ->with('subCategories')
                                 ->orderBy('sort');

            if ($type) {
                $query->where('type', $type);
            }

            $categories = $query->get()->map(function($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'icon' => $category->icon,
                    'type' => $category->type,
                    'sort' => $category->sort,
                    'description' => $category->description,
                    'subcategories' => $category->subCategories->map(function($sub) {
                        return [
                            'id' => $sub->id,
                            'name' => $sub->name,
                            'icon' => $sub->icon,
                            'sort' => $sub->sort,
                            'description' => $sub->description,
                        ];
                    })
                ];
            });

            return response()->json([
                'success' => true,
                'categories' => $categories
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取分类列表失败'
            ], 500);
        }
    }

    /**
     * 创建分类
     */
    public function store(Request $request, $bookId)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:50',
                'type' => 'required|integer|in:1,2',
                'description' => 'nullable|string|max:255',
                'icon' => 'nullable|string|max:10',
            ], [
                'name.required' => '分类名称不能为空',
                'name.max' => '分类名称不能超过50个字符',
                'type.required' => '分类类型不能为空',
                'type.in' => '分类类型无效',
                'description.max' => '分类描述不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 非会员用户一级分类数量限制
            if (!$user->isMember()) {
                $categoriesCount = MoneyCategory::where('book_id', $bookId)
                                              ->where('type', $request->type)
                                              ->count();
                if ($categoriesCount >= non_member_limits['max_categories_per_book']) {
                    return response()->json([
                        'success' => false,
                        'message' => '非会员用户每个账本最多创建'.non_member_limits['max_categories_per_book'].'个同类型的一级分类',
                        'redirect_to' => route('membership.benefits')
                    ], 403);
                }
            }

            // 检查同类型下是否已存在同名分类
            $existingCategory = MoneyCategory::where('book_id', $bookId)
                                           ->where('type', $request->type)
                                           ->where('name', $request->name)
                                           ->first();
            if ($existingCategory) {
                return response()->json([
                    'success' => false,
                    'message' => '该分类名称已存在'
                ], 422);
            }

            // 获取最大排序值
            $maxSort = MoneyCategory::where('book_id', $bookId)
                                  ->where('type', $request->type)
                                  ->max('sort') ?? 0;

            // 创建分类
            $category = MoneyCategory::create([
                'book_id' => $bookId,
                'name' => $request->name,
                'icon' => $request->icon ?? '📁',
                'type' => $request->type,
                'sort' => $maxSort + 1,
                'description' => $request->description,
            ]);

            return response()->json([
                'success' => true,
                'message' => '分类创建成功',
                'category' => [
                    'id' => $category->id,
                    'name' => $category->name,
                    'type' => $category->type,
                    'sort' => $category->sort,
                    'description' => $category->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建分类失败，请重试'
            ], 500);
        }
    }

    /**
     * 更新分类
     */
    public function update(Request $request, $bookId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 查找分类
            $category = MoneyCategory::where('book_id', $bookId)
                                   ->findOrFail($id);

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:50',
                'description' => 'nullable|string|max:255',
                'icon' => 'nullable|string|max:10',
            ], [
                'name.required' => '分类名称不能为空',
                'name.max' => '分类名称不能超过50个字符',
                'description.max' => '分类描述不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 检查同类型下是否已存在同名分类（排除自己）
            $existingCategory = MoneyCategory::where('book_id', $bookId)
                                           ->where('type', $category->type)
                                           ->where('name', $request->name)
                                           ->where('id', '!=', $id)
                                           ->first();
            if ($existingCategory) {
                return response()->json([
                    'success' => false,
                    'message' => '该分类名称已存在'
                ], 422);
            }

            // 更新分类
            $category->update([
                'name' => $request->name,
                'icon' => $request->icon ?? $category->icon,
                'description' => $request->description,
            ]);

            return response()->json([
                'success' => true,
                'message' => '分类更新成功',
                'category' => [
                    'id' => $category->id,
                    'name' => $category->name,
                    'type' => $category->type,
                    'sort' => $category->sort,
                    'description' => $category->description,
                    'icon' => $category->icon,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新分类失败，请重试'
            ], 500);
        }
    }

    /**
     * 删除分类
     */
    public function destroy(Request $request, $bookId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 查找分类
            $category = MoneyCategory::where('book_id', $bookId)
                                   ->findOrFail($id);

            // 检查是否有交易记录使用该分类
            $transactionCount = $category->transactions()->count();

            // 检查是否有自动交易记录使用该分类
            $autoTransactionCount = AutoMoneyTransaction::where('book_id', $bookId)
                                                     ->where('category_id', $id)
                                                     ->count();

            $totalCount = $transactionCount + $autoTransactionCount;

            if ($totalCount > 0) {
                // 获取同类型的其他分类，用于迁移选择
                $otherCategories = MoneyCategory::where('book_id', $bookId)
                                              ->where('type', $category->type)
                                              ->where('id', '!=', $id)
                                              ->get(['id', 'name', 'icon']);

                $message = '该分类下有';
                if ($transactionCount > 0) {
                    $message .= $transactionCount . '条交易记录';
                }

                if ($autoTransactionCount > 0) {
                    if ($transactionCount > 0) {
                        $message .= '和';
                    }
                    $message .= $autoTransactionCount . '条定时记账记录';
                }

                $message .= '，请先迁移这些记录';

                return response()->json([
                    'success' => false,
                    'message' => $message,
                    'transaction_count' => $transactionCount,
                    'auto_transaction_count' => $autoTransactionCount,
                    'total_count' => $totalCount,
                    'other_categories' => $otherCategories,
                    'require_migration' => true
                ], 422);
            }

            // 如果是仅检查模式，不执行删除操作
            if ($request->has('check_only') && $request->check_only) {
                return response()->json([
                    'success' => true,
                    'message' => '该分类下没有交易记录和自动交易记录，可以直接删除',
                    'has_transactions' => false,
                    'has_auto_transactions' => false
                ]);
            }

            // 删除分类（会级联删除子分类）
            $category->delete();

            return response()->json([
                'success' => true,
                'message' => '分类删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除分类失败，请重试: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新分类排序
     */
    public function updateSort(Request $request, $bookId)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'sort_data' => 'required|array',
                'sort_data.*.id' => 'required|integer',
                'sort_data.*.sort' => 'required|integer',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            DB::beginTransaction();

            // 更新排序
            foreach ($request->sort_data as $categoryData) {
                MoneyCategory::where('book_id', $bookId)
                           ->where('id', $categoryData['id'])
                           ->update([
                               'sort' => $categoryData['sort'],
                           ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '排序更新成功'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '更新排序失败，请重试'
            ], 500);
        }
    }

    /**
     * 显示子分类管理页面
     */
    public function subcategoryManagement($bookId, $categoryId)
    {
        $user = Auth::user();

        // 验证账本权限
        $book = MoneyBook::whereHas('users', function($query) use ($user) {
            $query->where('user_id', $user->id);
        })->findOrFail($bookId);

        // 获取主分类信息
        $category = MoneyCategory::where('book_id', $bookId)
                                ->findOrFail($categoryId);

        return view('user.subcategory-management', compact('book', 'category'));
    }

    /**
     * 获取子分类列表
     */
    public function getSubCategories($bookId, $categoryId)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证主分类存在
            $category = MoneyCategory::where('book_id', $bookId)
                                    ->findOrFail($categoryId);

            $subcategories = MoneySubCategory::where('book_id', $bookId)
                                           ->where('category_id', $categoryId)
                                           ->orderBy('sort')
                                           ->get()
                                           ->map(function($subcategory) {
                                               return [
                                                   'id' => $subcategory->id,
                                                   'name' => $subcategory->name,
                                                   'icon' => $subcategory->icon,
                                                   'sort' => $subcategory->sort,
                                                   'description' => $subcategory->description,
                                               ];
                                           });

            return response()->json([
                'success' => true,
                'subcategories' => $subcategories,
                'category' => [
                    'id' => $category->id,
                    'icon' => $category->icon,
                    'name' => $category->name,
                    'type' => $category->type,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取子分类列表失败'
            ], 500);
        }
    }

    /**
     * 创建子分类
     */
    public function storeSubCategory(Request $request, $bookId, $categoryId)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证分类存在
            $category = MoneyCategory::where('book_id', $bookId)
                                   ->findOrFail($categoryId);

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:50',
                'description' => 'nullable|string|max:255',
                'icon' => 'nullable|string|max:10',
            ], [
                'name.required' => '子分类名称不能为空',
                'name.max' => '子分类名称不能超过50个字符',
                'description.max' => '子分类描述不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 非会员用户二级分类数量限制
            if (!$user->isMember()) {
                $subCategoriesCount = MoneySubCategory::where('book_id', $bookId)
                                                   ->where('category_id', $categoryId)
                                                   ->count();
                if ($subCategoriesCount >= non_member_limits['max_subcategories_per_category']) {
                    return response()->json([
                        'success' => false,
                        'message' => '非会员用户每个一级分类最多创建'.non_member_limits['max_subcategories_per_category'].'个二级分类',
                        'redirect_to' => route('membership.benefits')
                    ], 403);
                }
            }

            // 检查是否已存在同名子分类
            $existingSubCategory = MoneySubCategory::where('book_id', $bookId)
                                                 ->where('category_id', $categoryId)
                                                 ->where('name', $request->name)
                                                 ->first();
            if ($existingSubCategory) {
                return response()->json([
                    'success' => false,
                    'message' => '该子分类名称已存在'
                ], 422);
            }

            // 获取最大排序值
            $maxSort = MoneySubCategory::where('category_id', $categoryId)
                                     ->max('sort') ?? 0;

            // 创建子分类
            $subCategory = MoneySubCategory::create([
                'book_id' => $bookId,
                'category_id' => $categoryId,
                'name' => $request->name,
                'icon' => $request->icon ?? '📁',
                'sort' => $maxSort + 1,
                'description' => $request->description,
            ]);

            return response()->json([
                'success' => true,
                'message' => '子分类创建成功',
                'subcategory' => [
                    'id' => $subCategory->id,
                    'name' => $subCategory->name,
                    'sort' => $subCategory->sort,
                    'description' => $subCategory->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建子分类失败，请重试'
            ], 500);
        }
    }

    /**
     * 更新子分类
     */
    public function updateSubCategory(Request $request, $bookId, $categoryId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 查找子分类
            $subCategory = MoneySubCategory::where('book_id', $bookId)
                                         ->where('category_id', $categoryId)
                                         ->findOrFail($id);

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:50',
                'description' => 'nullable|string|max:255',
                'icon' => 'nullable|string|max:10',
            ], [
                'name.required' => '子分类名称不能为空',
                'name.max' => '子分类名称不能超过50个字符',
                'description.max' => '子分类描述不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 检查是否已存在同名子分类（排除自己）
            $existingSubCategory = MoneySubCategory::where('book_id', $bookId)
                                                 ->where('category_id', $categoryId)
                                                 ->where('name', $request->name)
                                                 ->where('id', '!=', $id)
                                                 ->first();
            if ($existingSubCategory) {
                return response()->json([
                    'success' => false,
                    'message' => '该子分类名称已存在'
                ], 422);
            }

            // 更新子分类
            $subCategory->update([
                'name' => $request->name,
                'icon' => $request->icon ?? $subCategory->icon,
                'description' => $request->description,
            ]);

            return response()->json([
                'success' => true,
                'message' => '子分类更新成功',
                'subcategory' => [
                    'id' => $subCategory->id,
                    'name' => $subCategory->name,
                    'sort' => $subCategory->sort,
                    'description' => $subCategory->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新子分类失败，请重试'
            ], 500);
        }
    }

    /**
     * 删除子分类
     */
    public function destroySubCategory(Request $request, $bookId, $categoryId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 查找子分类
            $subCategory = MoneySubCategory::where('book_id', $bookId)
                                         ->where('category_id', $categoryId)
                                         ->findOrFail($id);

            // 检查是否有交易记录使用该子分类
            $transactionCount = $subCategory->transactions()->count();

            // 检查是否有自动交易记录使用该子分类
            $autoTransactionCount = AutoMoneyTransaction::where('book_id', $bookId)
                                                     ->where('sub_category_id', $id)
                                                     ->count();

            $totalCount = $transactionCount + $autoTransactionCount;

            if ($totalCount > 0) {
                // 获取同一主分类下的其他子分类，用于迁移选择
                $otherSubCategories = MoneySubCategory::where('book_id', $bookId)
                                                   ->where('category_id', $categoryId)
                                                   ->where('id', '!=', $id)
                                                   ->get(['id', 'name', 'icon']);

                $message = '该子分类下有';
                if ($transactionCount > 0) {
                    $message .= $transactionCount . '条交易记录';
                }

                if ($autoTransactionCount > 0) {
                    if ($transactionCount > 0) {
                        $message .= '和';
                    }
                    $message .= $autoTransactionCount . '条定时记账记录';
                }

                $message .= '，请先迁移这些记录';

                return response()->json([
                    'success' => false,
                    'message' => $message,
                    'transaction_count' => $transactionCount,
                    'auto_transaction_count' => $autoTransactionCount,
                    'total_count' => $totalCount,
                    'other_subcategories' => $otherSubCategories,
                    'require_migration' => true
                ], 422);
            }

            // 如果是仅检查模式，不执行删除操作
            if ($request->has('check_only') && $request->check_only) {
                return response()->json([
                    'success' => true,
                    'message' => '该子分类下没有交易记录和自动交易记录，可以直接删除',
                    'has_transactions' => false,
                    'has_auto_transactions' => false
                ]);
            }

            // 删除子分类
            $subCategory->delete();

            return response()->json([
                'success' => true,
                'message' => '子分类删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除子分类失败，请重试: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 迁移分类下的交易记录并删除分类
     */
    public function migrateAndDestroy(Request $request, $bookId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证输入
            $validator = Validator::make($request->all(), [
                'target_category_id' => 'required|integer|exists:money_categories,id',
                'target_subcategory_id' => 'nullable|integer|exists:money_sub_categories,id',
            ], [
                'target_category_id.required' => '请选择目标分类',
                'target_category_id.exists' => '目标分类不存在',
                'target_subcategory_id.exists' => '目标子分类不存在',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 查找源分类
            $sourceCategory = MoneyCategory::where('book_id', $bookId)
                                         ->findOrFail($id);

            // 查找目标分类
            $targetCategory = MoneyCategory::where('book_id', $bookId)
                                         ->findOrFail($request->target_category_id);

            // 确保源分类和目标分类类型相同
            if ($sourceCategory->type != $targetCategory->type) {
                return response()->json([
                    'success' => false,
                    'message' => '源分类和目标分类类型不一致'
                ], 422);
            }
            DB::beginTransaction();

            // 查找目标子分类（如果提供）
            $targetSubCategory = null;
            if ($request->has('target_subcategory_id') && $request->target_subcategory_id) {
                $targetSubCategory = MoneySubCategory::where('book_id', $bookId)
                                                  ->where('category_id', $request->target_category_id)
                                                  ->findOrFail($request->target_subcategory_id);
            }

            // 获取源分类下的所有交易记录
            $transactions = $sourceCategory->transactions;
            $transactionCount = $transactions->count();

            // 更新交易记录的分类ID
            foreach ($transactions as $transaction) {
                $transaction->category_id = $targetCategory->id;
                $transaction->sub_category_id = $targetSubCategory ? $targetSubCategory->id : null;
                $transaction->save();
            }

            // 获取源分类下的所有自动交易记录
            $autoTransactions = AutoMoneyTransaction::where('book_id', $bookId)
                                                 ->where('category_id', $sourceCategory->id)
                                                 ->get();
            $autoTransactionCount = $autoTransactions->count();

            // 更新自动交易记录的分类ID
            foreach ($autoTransactions as $autoTransaction) {
                $autoTransaction->category_id = $targetCategory->id;
                $autoTransaction->sub_category_id = $targetSubCategory ? $targetSubCategory->id : null;
                $autoTransaction->save();
            }

            // 删除源分类（会级联删除子分类）
            $sourceCategory->delete();

            DB::commit();

            // 构建成功消息
            $message = '成功';
            if ($transactionCount > 0) {
                $message .= '迁移' . $transactionCount . '条交易记录';
            }

            if ($autoTransactionCount > 0) {
                if ($transactionCount > 0) {
                    $message .= '和';
                } else {
                    $message .= '迁移';
                }
                $message .= $autoTransactionCount . '条自动交易记录';
            }

            $message .= '并删除分类';

            return response()->json([
                'success' => true,
                'message' => $message,
                'transaction_count' => $transactionCount,
                'auto_transaction_count' => $autoTransactionCount
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '迁移失败，请重试: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 迁移子分类下的交易记录并删除子分类
     */
    public function migrateAndDestroySubCategory(Request $request, $bookId, $categoryId, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证输入
            $validator = Validator::make($request->all(), [
                'target_subcategory_id' => 'required|integer|exists:money_sub_categories,id',
            ], [
                'target_subcategory_id.required' => '请选择目标子分类',
                'target_subcategory_id.exists' => '目标子分类不存在',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 查找源子分类
            $sourceSubCategory = MoneySubCategory::where('book_id', $bookId)
                                              ->where('category_id', $categoryId)
                                              ->findOrFail($id);

            // 查找目标子分类
            $targetSubCategory = MoneySubCategory::where('book_id', $bookId)
                                              ->findOrFail($request->target_subcategory_id);

            // 允许跨主分类迁移子分类

            DB::beginTransaction();

            // 获取源子分类下的所有交易记录
            $transactions = $sourceSubCategory->transactions;
            $transactionCount = $transactions->count();

            // 更新交易记录的子分类ID
            foreach ($transactions as $transaction) {
                $transaction->category_id = $targetSubCategory->category_id;
                $transaction->sub_category_id = $targetSubCategory->id;
                $transaction->save();
            }

            // 获取源子分类下的所有自动交易记录
            $autoTransactions = AutoMoneyTransaction::where('book_id', $bookId)
                                                 ->where('sub_category_id', $sourceSubCategory->id)
                                                 ->get();
            $autoTransactionCount = $autoTransactions->count();

            // 更新自动交易记录的子分类ID
            foreach ($autoTransactions as $autoTransaction) {
                $autoTransaction->category_id = $targetSubCategory->category_id;
                $autoTransaction->sub_category_id = $targetSubCategory->id;
                $autoTransaction->save();
            }

            // 删除源子分类
            $sourceSubCategory->delete();

            DB::commit();

            // 构建成功消息
            $message = '成功';
            if ($transactionCount > 0) {
                $message .= '迁移' . $transactionCount . '条交易记录';
            }

            if ($autoTransactionCount > 0) {
                if ($transactionCount > 0) {
                    $message .= '和';
                } else {
                    $message .= '迁移';
                }
                $message .= $autoTransactionCount . '条自动交易记录';
            }

            $message .= '并删除子分类';

            return response()->json([
                'success' => true,
                'message' => $message,
                'transaction_count' => $transactionCount,
                'auto_transaction_count' => $autoTransactionCount
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '迁移失败，请重试: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新子分类排序
     */
    public function updateSubCategorySort(Request $request, $bookId, $categoryId)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 验证主分类存在
            $category = MoneyCategory::where('book_id', $bookId)
                                    ->findOrFail($categoryId);

            $sortData = $request->input('sort_data', []);

            DB::beginTransaction();

            foreach ($sortData as $item) {
                MoneySubCategory::where('book_id', $bookId)
                               ->where('category_id', $categoryId)
                               ->where('id', $item['id'])
                               ->update(['sort' => $item['sort']]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '子分类排序更新成功'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '更新子分类排序失败，请重试'
            ], 500);
        }
    }
}
